<template>
  <view class="skill-tree-bg">
    <!-- 时间选择器 -->
    <view class="time-filter-bar">
      <view class="filter-title">时间筛选</view>
      <view class="date-picker-group">
        <view class="date-picker-item">
          <text class="date-label">开始时间</text>
          <!-- #ifdef MP-WEIXIN || APP-PLUS -->
          <picker mode="date" :value="tempStartDate" :start="minDate" :end="maxDate" @change="onStartDateChange" class="date-picker">
            <view class="date-display">{{ tempStartDate || '选择日期' }}</view>
          </picker>
          <!-- #endif -->
          <!-- #ifdef H5 -->
          <input type="date" v-model="tempStartDate" :min="minDate" :max="maxDate" class="date-input" @change="onDateChange" />
          <!-- #endif -->
        </view>
        <view class="date-picker-item">
          <text class="date-label">结束时间</text>
          <!-- #ifdef MP-WEIXIN || APP-PLUS -->
          <picker mode="date" :value="tempEndDate" :start="tempStartDate || minDate" :end="maxDate" @change="onEndDateChange" class="date-picker">
            <view class="date-display">{{ tempEndDate || '选择日期' }}</view>
          </picker>
          <!-- #endif -->
          <!-- #ifdef H5 -->
          <input type="date" v-model="tempEndDate" :min="tempStartDate || minDate" :max="maxDate" class="date-input" @change="onDateChange" />
          <!-- #endif -->
        </view>
        <view class="date-picker-item">
          <button class="reset-btn" @tap="resetToDefault">重置</button>
          <button class="apply-btn" @tap="applyTimeFilter">应用</button>
        </view>
      </view>
    </view>

    <!-- 加载中 -->
    <view v-if="loading" class="loading-container">
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 空状态 -->
    <view v-else-if="totalBadges === 0" class="empty-state">
      <view class="empty-icon">🌳</view>
      <text class="empty-title">暂无技能树</text>
      <text class="empty-desc">该时间段内你还没有任何徽章，快去完成任务吧！</text>
      <button class="goto-tasks-btn" @click="goToTasks">去完成任务</button>
    </view>
    
    <!-- 有数据时显示技能树 -->
    <view v-else class="skill-tree-root">
      <SkillTreeNode
        v-for="(node, key) in treeStats"
        :key="key"
        :node="node"
        :level="1"
        :getName="getNameByPath"
        :uid="uid"
      />
    </view>
  </view>
</template>

<script setup>
import { NETWORK_CONFIG } from '@/config/network.js'
import SkillTreeNode from './SkillTreeNode.vue'
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { categories } from '@/utils/skillUtils'
import BackButton from '@/components/BackButton.vue'

const uid = ref('')
const today = new Date()
const lastYear = new Date()
lastYear.setFullYear(today.getFullYear() - 1)
const tenYearsAgo = new Date()
tenYearsAgo.setFullYear(today.getFullYear() - 10)

const formatDate = (date) => date.toISOString().slice(0, 10)
const startDate = ref(formatDate(lastYear))
const endDate = ref(formatDate(today))
const minDate = ref(formatDate(tenYearsAgo))
const maxDate = ref(formatDate(today))

const loading = ref(false)
const error = ref('')
const totalBadges = ref(0)
const treeStats = ref({})
const tempStartDate = ref(formatDate(lastYear))
const tempEndDate = ref(formatDate(today))

function getNameByPath(path) {
  if (!path) return ''
  if (path.length === 2) {
    const cat = categories.find(c => c.code === path)
    return cat ? cat.name : path
  }
  if (path.length === 4) {
    for (const cat of categories) {
      const sub = cat.subcategories.find(s => s.code === path)
      if (sub) return sub.name
    }
    return path
  }
  if (path.length === 6) {
    for (const cat of categories) {
      for (const sub of cat.subcategories) {
        const dir = sub.directions.find(d => d.code === path)
        if (dir) return dir.name
      }
    }
    return path
  }
  return path
}

async function fetchTree() {
  loading.value = true
  error.value = ''
  try {
    const token = uni.getStorageSync('accessToken')
    const res = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/badge/skill-tree`,
      method: 'GET',
      data: {
        uid: uid.value,
        start: startDate.value + 'T00:00:00',
        end: endDate.value + 'T23:59:59'
      },
      header: { 'Access-Token': `Bearer ${token}` }
    })
    // 兼容 uni.request 返回 { data, statusCode, ... }
    if (res && res.data) {
      totalBadges.value = res.data.totalBadges
      treeStats.value = res.data.treeStats
      console.log('Tree data loaded:', res.data)
      console.log('Tree stats:', treeStats.value)
      console.log('Tree stats keys:', Object.keys(treeStats.value))
      console.log('Tree stats values:', Object.values(treeStats.value))
    }
  } catch (e) {
    error.value = e?.errMsg || e?.message || '加载失败'
  } finally {
    loading.value = false
  }
}

// 时间选择器事件处理
function onStartDateChange(e) {
  tempStartDate.value = e.detail.value
}

function onEndDateChange(e) {
  tempEndDate.value = e.detail.value
}

function onDateChange() {
  // H5端自动更新
  tempStartDate.value = startDate.value
  tempEndDate.value = endDate.value
}

// 重置到默认时间（过去一年）
function resetToDefault() {
  tempStartDate.value = formatDate(lastYear)
  tempEndDate.value = formatDate(today)
  startDate.value = tempStartDate.value
  endDate.value = tempEndDate.value
  fetchTree()
}

// 应用时间筛选
function applyTimeFilter() {
  if (tempStartDate.value && tempEndDate.value) {
    if (tempStartDate.value > tempEndDate.value) {
      uni.showToast({
        title: '开始时间不能晚于结束时间',
        icon: 'none'
      })
      return
    }
    startDate.value = tempStartDate.value
    endDate.value = tempEndDate.value
    fetchTree()
  } else {
    uni.showToast({
      title: '请选择开始和结束时间',
      icon: 'none'
    })
  }
}

// 跳转到任务列表
function goToTasks() {
  uni.switchTab({
    url: '/pages/index/index'
  })
}

onLoad((options) => {
  uid.value = options.uid || ''
  console.log('Skill tree page loaded with uid:', uid.value)
  fetchTree()
})
</script>

<style scoped>
.skill-tree-bg {
  background: #0a1833;
  min-height: 100vh;
  position: relative;
  overflow-x: auto;
}

/* 时间筛选栏 */
.time-filter-bar {
  background: linear-gradient(135deg, #1e3a5f 0%, #2d4a6f 100%);
  padding: 20rpx 40rpx;
  border-radius: 16rpx;
  margin: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.2);
}

.filter-title {
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.date-picker-group {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.date-picker-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.date-label {
  color: #a0d3ff;
  font-size: 28rpx;
  min-width: 140rpx;
}

.date-picker {
  flex: 1;
}

.date-display {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  padding: 20rpx 24rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  border: 2rpx solid rgba(255, 255, 255, 0.2);
}

.date-input {
  flex: 1;
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  padding: 20rpx 24rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  border: 2rpx solid rgba(255, 255, 255, 0.2);
}

.reset-btn, .apply-btn {
  flex: 1;
  padding: 20rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: bold;
  border: none;
  transition: all 0.3s;
}

.reset-btn {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
}

.reset-btn:active {
  background: rgba(255, 255, 255, 0.3);
}

.apply-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

.apply-btn:active {
  opacity: 0.8;
}

/* 加载中状态 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

.loading-text {
  color: #fff;
  font-size: 32rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 60rpx;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 40rpx;
}

.empty-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #fff;
  margin-bottom: 20rpx;
}

.empty-desc {
  font-size: 28rpx;
  color: #aaa;
  margin-bottom: 60rpx;
  text-align: center;
}

.goto-tasks-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border: none;
  border-radius: 50rpx;
  padding: 20rpx 60rpx;
  font-size: 32rpx;
  font-weight: bold;
  box-shadow: 0 10rpx 30rpx rgba(102, 126, 234, 0.3);
}

.goto-tasks-btn:active {
  opacity: 0.8;
}

.skill-tree-root {
  position: relative;
  padding: 60px 0;
  display: flex;
  justify-content: flex-start;
  width: max-content;      /* 关键：内容宽度自适应所有节点 */
  overflow-x: visible;     /* 由外层控制滚动 */
  overflow-y: visible;
  white-space: nowrap;
}
.tree-children.level-1 { gap: 600px; }
.tree-children.level-2 { gap: 240px; }
.tree-children.level-3, .tree-children.level-4, .tree-children.level-5 { gap: 60px; }
.skill-tree-root::-webkit-scrollbar {
  height: 8px;
  background: #1a2a44;
}
.skill-tree-root::-webkit-scrollbar-thumb {
  background: #36a;
  border-radius: 4px;
}
</style>